import { useEffect } from 'react'

const M = number => (number > 0 ? Math.floor(number) : Math.ceil(number))

const formatTime = number => {
  const hours = M((number % (1e3 * 60 * 60 * 24)) / (1e3 * 60 * 60))
  const minutes = M((number % (1e3 * 60 * 60)) / (1e3 * 60))
  const seconds = M((number % (1e3 * 60)) / 1e3)

  const h = String(hours).padStart(2, '0')
  const m = String(minutes).padStart(2, '0')
  const s = String(seconds).padStart(2, '0')
  console.log('%c Line:19 🥤 formatTime', 'color:#6ec1c2', `${h}:${m}:${s}`)
  return `${h}:${m}:${s}`
}

function useCountdown() {
  let countdownTimer = null

  function isCountdownRunning() {
    return countdownTimer !== null
  }

  /**
   * 开始倒计时
   * @param number seconds 倒计时秒数
   * @param function callback 倒计时回调函数, 接收参数为倒计时剩余时间
   * @return function 停止倒计时函数
   */
  function startCountdownTimer(duration, fn) {
    stopCountdownTimer()

    countdownTimer = setInterval(() => {
      duration -= 1
      fn(formatTime(duration * 1e3))
    }, 1000)

    return () => clearInterval(countdownTimer)
  }

  function stopCountdownTimer() {
    countdownTimer && clearInterval(countdownTimer)
  }

  useEffect(() => {
    return () => stopCountdownTimer()
  }, [])

  return { isCountdownRunning, formatTime, stopCountdownTimer, startCountdownTimer }
}

export default useCountdown
